package com.hadluo.qq.client.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hadluo.qq.client.model.UserInfo;
import com.hadluo.qq.client.utils.Constants;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class CreateGroupDialog extends JDialog {
    private UserInfo currentUser;
    private JTextField groupNameField;
    private JTextArea descriptionArea;
    private JList<UserInfo> friendList;
    private DefaultListModel<UserInfo> friendListModel;
    private JButton createButton;
    private JButton cancelButton;

    public CreateGroupDialog(Frame owner, UserInfo currentUser) {
        super(owner, "创建群聊", true);
        this.currentUser = currentUser;
        initializeUI();
        loadFriendList();
    }

    private void initializeUI() {
        setSize(400, 600);
        setLocationRelativeTo(getOwner());
        setLayout(new BorderLayout());
        getContentPane().setBackground(new Color(35, 35, 35));

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(new Color(35, 35, 35));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBackground(new Color(35, 35, 35));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        // 群名称输入
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel nameLabel = new JLabel("群名称:");
        nameLabel.setForeground(Color.WHITE);
        formPanel.add(nameLabel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        groupNameField = new JTextField(20);
        styleTextField(groupNameField);
        formPanel.add(groupNameField, gbc);

        // 群描述输入
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0;
        JLabel descLabel = new JLabel("群描述:");
        descLabel.setForeground(Color.WHITE);
        formPanel.add(descLabel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        descriptionArea = new JTextArea(3, 20);
        styleTextArea(descriptionArea);
        JScrollPane descScrollPane = new JScrollPane(descriptionArea);
        descScrollPane.setBorder(null);
        formPanel.add(descScrollPane, gbc);

        // 好友列表
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;

        JLabel friendLabel = new JLabel("选择好友:");
        friendLabel.setForeground(Color.WHITE);
        formPanel.add(friendLabel, gbc);

        gbc.gridy = 3;
        friendListModel = new DefaultListModel<>();
        friendList = new JList<>(friendListModel);
        friendList.setBackground(new Color(45, 45, 45));
        friendList.setForeground(Color.WHITE);
        friendList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        friendList.setCellRenderer(new FriendListRenderer());

        JScrollPane friendScrollPane = new JScrollPane(friendList);
        friendScrollPane.setBorder(null);
        formPanel.add(friendScrollPane, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.setBackground(new Color(35, 35, 35));

        createButton = new JButton("创建群聊");
        styleButton(createButton);
        createButton.addActionListener(e -> handleCreateGroup());

        cancelButton = new JButton("取消");
        styleButton(cancelButton);
        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(createButton);
        buttonPanel.add(cancelButton);

        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void loadFriendList() {
        new Thread(() -> {
            try {
                String url = "http://"+ Constants.SERVER_HOST+":8080/api/friend/list?qqNumber=" + currentUser.getQqNumber();
                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("GET");

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }

                        JSONObject jsonResponse = JSON.parseObject(response.toString());
                        if (jsonResponse.getBoolean("success")) {
                            JSONArray friends = jsonResponse.getJSONArray("data");
                            SwingUtilities.invokeLater(() -> {
                                friendListModel.clear();
                                for (int i = 0; i < friends.size(); i++) {
                                    JSONObject friendJson = friends.getJSONObject(i);
                                    UserInfo friend = new UserInfo();
                                    friend.setQqNumber(friendJson.getString("qqNumber"));
                                    friend.setNickname(friendJson.getString("nickname"));
                                    friend.setAvatar(friendJson.getString("avatar"));
                                    friendListModel.addElement(friend);
                                }
                            });
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                            "加载好友列表失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }

    private void handleCreateGroup() {
        String groupName = groupNameField.getText().trim();
        if (groupName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入群名称", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        List<UserInfo> selectedFriends = friendList.getSelectedValuesList();
        if (selectedFriends.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请选择至少一个好友", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 准备请求数据
        JSONObject requestData = new JSONObject();
        requestData.put("ownerQQNumber", currentUser.getQqNumber());
        requestData.put("groupName", groupName);
        requestData.put("description", descriptionArea.getText().trim());

        List<String> memberQQNumbers = new ArrayList<>();
        memberQQNumbers.add(currentUser.getQqNumber()); // 添加群主
        for (UserInfo friend : selectedFriends) {
            memberQQNumbers.add(friend.getQqNumber());
        }
        requestData.put("memberQQNumbers", memberQQNumbers);

        // 发送创建群组请求
        new Thread(() -> {
            try {
                String url = "http://"+Constants.SERVER_HOST+":8080/api/group/create";
                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);

                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = requestData.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }

                        JSONObject jsonResponse = JSON.parseObject(response.toString());
                        boolean success = jsonResponse.getBoolean("success");
                        String message = jsonResponse.getString("message");

                        SwingUtilities.invokeLater(() -> {
                            if (success) {
                                JOptionPane.showMessageDialog(this,
                                        "群创建成功",
                                        "成功",
                                        JOptionPane.INFORMATION_MESSAGE);
                                dispose();
                            } else {
                                JOptionPane.showMessageDialog(this,
                                        message,
                                        "创建失败",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                            "创建群组失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }

    private void styleTextField(JTextField textField) {
        textField.setBackground(new Color(45, 45, 45));
        textField.setForeground(Color.WHITE);
        textField.setCaretColor(Color.WHITE);
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(60, 60, 60)),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    }

    private void styleTextArea(JTextArea textArea) {
        textArea.setBackground(new Color(45, 45, 45));
        textArea.setForeground(Color.WHITE);
        textArea.setCaretColor(Color.WHITE);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(60, 60, 60)),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    }

    private void styleButton(JButton button) {
        button.setBackground(new Color(29, 185, 84));
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 20));

        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(30, 215, 96));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(29, 185, 84));
            }
        });
    }

    // 好友列表渲染器
    private class FriendListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            UserInfo friend = (UserInfo) value;
            JPanel panel = new JPanel(new BorderLayout(10, 0));
            panel.setBackground(isSelected ? new Color(55, 55, 55) : new Color(45, 45, 45));
            panel.setBorder(new EmptyBorder(5, 5, 5, 5));

            // 创建头像标签
            JLabel avatarLabel = new JLabel();
            avatarLabel.setPreferredSize(new Dimension(30, 30));
            avatarLabel.setBackground(new Color(60, 60, 60));
            avatarLabel.setOpaque(true);
            avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);

            // 设置头像或显示昵称首字
            if (friend.getAvatar() != null && !friend.getAvatar().isEmpty()) {
                try {
                    String avatarUrl = friend.getAvatar();
                    if (!avatarUrl.startsWith("http")) {
                        avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                    }
                    ImageIcon imageIcon = new ImageIcon(new URL(avatarUrl));
                    Image image = imageIcon.getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH);
                    avatarLabel.setIcon(new ImageIcon(image));
                } catch (Exception e) {
                    avatarLabel.setText(friend.getNickname().substring(0, 1));
                    avatarLabel.setForeground(Color.WHITE);
                    avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
                }
            } else {
                avatarLabel.setText(friend.getNickname().substring(0, 1));
                avatarLabel.setForeground(Color.WHITE);
                avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
            }

            // 创建昵称标签
            JLabel nicknameLabel = new JLabel(friend.getNickname());
            nicknameLabel.setForeground(Color.WHITE);
            nicknameLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

            panel.add(avatarLabel, BorderLayout.WEST);
            panel.add(nicknameLabel, BorderLayout.CENTER);

            return panel;
        }
    }
}